package com.huotao.filter;

import com.huotao.constant.Constants;
import com.huotao.domain.bean.StatelessToken;
import org.apache.shiro.web.filter.AccessControlFilter;
import org.apache.shiro.web.servlet.ShiroHttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 项目名称：CaiHai
 * <br>类描述：
 * <br>创建人：htliu
 * <br>创建时间：2017/9/19 10:57
 * <br>修改人:
 * <br>修改时间：2017/9/19 10:57
 * <br>修改备注：
 * <br>@version
 */
public class StatelessAuthcFilter extends AccessControlFilter {
    private static final Logger LOGGER = LoggerFactory.getLogger(StatelessAuthcFilter.class);
    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
        return false;
    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        ShiroHttpServletRequest shiroHttpServletRequest = (ShiroHttpServletRequest) request;
        //1、客户端生成的消息摘要
        String accessToken = shiroHttpServletRequest.getHeader(Constants.PARAM_TOKEN);
        //2、客户端传入的用户身份
        String username = shiroHttpServletRequest.getHeader(Constants.PARAM_USERNAME);
        LOGGER.info("onAccessDenied:  username= " + username);
        LOGGER.info("onAccessDenied:  accessToken= " + accessToken);
        //4、生成无状态Token
        StatelessToken token = new StatelessToken(username, accessToken);
        try {
            //5、委托给Realm进行登录
            getSubject(request, response).login(token);
        } catch (Exception e) {
            e.printStackTrace();
            //6、登录失败
            onLoginFail(response);
            return false;
        }
        return true;
    }

    /**
     * 登录失败时默认返回401状态码
     *
     * @param response
     * @throws IOException
     */
    private void onLoginFail(ServletResponse response) throws IOException {
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        httpResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        httpResponse.getWriter().write("login error");
    }
}
